#include "VertexFormats.fx"
#include "Fog.fx"

float4x4 world_view_proj : WORLD_VIEW_PROJECTION;
float3 camera_pos : CAMERA_POS;
float time : TIME;

float fog_start = 50.0f;
float fog_end = 60.0f;

float start_time = 22.0f;
float fadein_length = 2.5f;

struct VSOut
{
	float4 pos : POSITION;
	float2 uv : TEXCOORD0;
	float3 world_pos : TEXCOORD1;
	float t : TEXCOORD2;
};

texture tex : TUNNEL_TEXTURE;

sampler tex_sampler =
sampler_state 
{
	Texture = <tex>;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
};	

float2 rotate(float2 v, float angle) {
	float s, c;
	sincos(angle, s, c);
	return float2(c * v.x - s * v.y, s * v.x + c * v.y);
}	

VSOut VS_Tunnel(VertexPosUV input)
{
	VSOut output;
	input.pos.yz = rotate(input.pos.yz, time/20);
	input.pos.yz *= 2.5;
	output.world_pos = input.pos;
	output.pos = mul(float4(input.pos, 1), world_view_proj);
	output.uv = input.uv;
	output.t = saturate((time - start_time) / fadein_length);
	return output;
}

VSOut VS_TunnelOuter(VertexPosUV input)
{
	VSOut output;
	input.pos.yz = rotate(input.pos.yz, time/30);
	input.pos.yz *= -3.2;
	output.world_pos = input.pos;
	output.pos = mul(float4(input.pos, 1), world_view_proj);
	output.uv = input.uv;
	output.t = saturate((time - start_time) / fadein_length);
	return output;
}

float4 PS_Tunnel(VSOut input) : COLOR
{
	input.uv.y += sin(input.world_pos.x/10) * smoothstep(1, 0, input.t);	
	float4 fog_color = float4(quadraticFog(input.world_pos, camera_pos,
		float3(1, 1, 1), float3(0, 0, 0), fog_start, fog_end), 1);
	return tex2D(tex_sampler, input.uv) * 0.4 * fog_color * input.t;
}

technique t0
{
	pass p0
	{
		VertexShader = compile vs_2_0 VS_Tunnel();
		PixelShader = compile ps_2_0 PS_Tunnel();

		AlphaBlendEnable = true;
		SrcBlend = srcAlpha;
		DestBlend = one;
		ZEnable = false;
		CullMode = None;
	}
}

technique t1
{
	pass p0
	{
		VertexShader = compile vs_2_0 VS_TunnelOuter();
		PixelShader = compile ps_2_0 PS_Tunnel();

		AlphaBlendEnable = true;
		SrcBlend = srcAlpha;
		DestBlend = one;
		ZEnable = false;
		CullMode = None;
	}
}

